package com.hxzy.shop.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hxzy.shop.common.dto.store.StoreMapStructConvert;
import com.hxzy.shop.common.dto.store.req.ChangeStorePwdReq;
import com.hxzy.shop.common.dto.store.req.StoreListReq;
import com.hxzy.shop.common.dto.store.resp.SameCityDeliveryResp;
import com.hxzy.shop.common.dto.store.resp.StoreDetailResp;
import com.hxzy.shop.common.dto.store.resp.StoreListResp;
import com.hxzy.shop.common.dto.store.resp.StoreNumResp;
import com.hxzy.shop.common.redis.RedisService;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.constant.RedisConstant;
import com.hxzy.shop.entity.MtShop;
import com.hxzy.shop.entity.Store;
import com.hxzy.shop.entity.StoreAccount;
import com.hxzy.shop.entity.StoreInnerQualification;
import com.hxzy.shop.feign.merchant.MerchantFeign;
import com.hxzy.shop.mapper.MtShopMapper;
import com.hxzy.shop.mapper.StoreAccountMapper;
import com.hxzy.shop.mapper.StoreInnerQualificationMapper;
import com.hxzy.shop.mapper.StoreMapper;
import com.hxzy.shop.properties.RSAProperties;
import com.hxzy.shop.service.StoreService;
import com.hxzy.shop.utils.RsaUtils;
import com.hxzy.shop.utils.WebUtil;
import com.hxzy.shop.vo.ApiException;
import com.hxzy.shop.vo.Result;
import com.hxzy.shop.vo.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 功能描述:门店服务实现
 *
 * @author tonneyyy
 */
@Service
//@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store>implements StoreService {

    /**
     * 门店信息
     */
    @Autowired
    private StoreMapper storeMapper;

    /**
     *  门店账户
     */
    @Autowired
    private StoreAccountMapper storeAccountMapper;

    /**
     * 美团服务商户
     */
    @Autowired
    private MtShopMapper mtShopMapper;

    @Autowired
    private MerchantFeign merchantFeign;

    @Autowired
    private RedisService redisService;

    /**
     * 门店关联资质
     */
    @Autowired
    private StoreInnerQualificationMapper storeInnerQualificationMapper;

    @Resource
    private RSAProperties rsaProperties;



    /**
     * 分页查询门店列表
     * @param req
     * @return
     */
    @Override
    public PageInfo<StoreListResp> storeList(StoreListReq req) {

        return PageHelper.startPage(req.getPageNumber(),req.getPageSize())
                .doSelectPageInfo(()->{
                   storeMapper.storeList(req);
                });
    }

    /**
     * 商户总店数量以及已开店数量
     * @return
     */
    @Override
    public StoreNumResp storeNum() {
        StoreNumResp resp = new StoreNumResp();
        resp.setOpenStore(storeMapper.selectStoreCount());
        resp.setNewStore(storeMapper.selectMerchantStoreCount());
        return resp;
    }

    /**
     * 门店详情
     * @param storeId
     * @return
     */
    @Override
    public StoreDetailResp storeDetail(Long storeId) {
        Store store = this.storeMapper.selectById(storeId);
        if (ObjectUtils.isEmpty(store)) {
            throw new ApiException(500, "门店不存在");
        }

        //根据门店id查找管理员账号
        StoreAccount storeAccount = this.storeAccountMapper.selectOne(new LambdaQueryWrapper<StoreAccount>()
                .eq(StoreAccount::getStoreId, storeId)
                .eq(StoreAccount::getRoot, Boolean.TRUE));
        //解密
        storeAccount.setPassword(RsaUtils.pubDec(storeAccount.getPwd(), rsaProperties.getPrivateKeyStr(), rsaProperties.getPublicKeyStr()));
        //复制对象
        StoreDetailResp storeDetailResp = StoreMapStructConvert.INSTANCE.toResp(store);
        storeDetailResp.setStoreId(storeId);
        storeDetailResp.setAccount(storeAccount.getAccount());
        storeDetailResp.setPassword(storeAccount.getPassword());

        //配送方式 0支持快递 1支持同城 2支持自提
        List<Integer> list = new ArrayList<>();
        //是否支持快递
        if (!ObjectUtils.isEmpty(store.getB2c()) && store.getB2c()) {
            list.add(0);
        }
        //查询同城配送
        if (!ObjectUtils.isEmpty(store.getO2o()) && store.getO2o()) {
            list.add(1);
        }
        //是否支持自提
        if (!ObjectUtils.isEmpty(store.getSelfTake()) && store.getSelfTake()) {
            list.add(2);
        }
        //设置配送方式
        storeDetailResp.setDeliveryMethod(list);

        //查询门店资质
        List<String> qualifications = this.storeInnerQualificationMapper.qalificationAddressByStoreId(storeId);

        if (qualifications.size() != 0) {
            storeDetailResp.setQalificationAddress(qualifications);
        }

        //开通美团服务商 是否支持同城
        Integer integer = mtShopMapper.selectCount(new LambdaQueryWrapper<MtShop>().eq(MtShop::getShopId, storeId));
        if (integer > 0) {
            storeDetailResp.setIsMtDelivery(true);
        } else {
            storeDetailResp.setIsMtDelivery(false);
        }

        return storeDetailResp;
    }

    /**
     * 判断门店是否支持门店配送
     * @param storeId
     * @return
     */
    @Override
    public SameCityDeliveryResp checkSameCityDelivery(Long storeId) {
        LambdaQueryWrapper<MtShop> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MtShop::getShopId,storeId).in(MtShop::getStatus,40,30);

        MtShop mtShop = this.mtShopMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(mtShop)) {
            return new SameCityDeliveryResp(false, null);
        }
        //支持门店配送(美团)
        return new SameCityDeliveryResp(true,mtShop.getScope());
    }

    /**
     * 修改门店帐号和密码
     * @param req
     * @return
     */
    @Override
    public boolean changeStorePwd(ChangeStorePwdReq req) {
        //根据门店id查找门店账号信息
        LambdaQueryWrapper<StoreAccount> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StoreAccount::getStoreId,req.getStoreId()).eq(StoreAccount::getRoot,Boolean.TRUE);
        StoreAccount account = this.storeAccountMapper.selectOne(queryWrapper);
        if (ObjectUtil.isEmpty(account)) {
            throw new ApiException(500, "门店账号不存在");
        }
        //查询账号是否重复
        StoreAccount storeAccount = storeAccountMapper.selectOne(new LambdaQueryWrapper<StoreAccount>()
                .eq(StoreAccount::getMerchantId, account.getMerchantId())
                .eq(StoreAccount::getAccount, req.getAccount())
                .ne(StoreAccount::getAccount, account.getAccount()));
        if (ObjectUtil.isNotEmpty(storeAccount)) {
            throw new ApiException(500, "门店账号已存在");
        }
        //设置账号
        account.setAccount(req.getAccount());
        String password = req.getPassword();

        if (!BCrypt.checkpw(password, account.getPassword())) {
            account.setPassword(BCrypt.hashpw(password));
            account.setPwd(RsaUtils.priEnc(password, rsaProperties.getPrivateKeyStr(), rsaProperties.getPublicKeyStr()));
            //多线程异步任务
            CompletableFuture.runAsync(() -> {
                String key = RedisConstant.AUTHORIZATION + AuthConstant.ADMIN_SLAVE_CLIENT_ID + "_" + account.getAccount();
                redisService.emptyToken(key);
            });
        }

        account.setUpdateTime(new Date());
        int result = this.storeAccountMapper.updateById(account);
        return result>0;
    }


}
